package com.example.demo.order;

import com.example.demo.common.Constant;
import com.example.demo.repo.RepertoryCache;
import com.example.demo.repo.RepertoryRepo;
import com.example.demo.repo.Repo;
import com.example.demo.repo.model.Order;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.example.demo.common.Constant.ORDER_PREVIEW;
import static com.example.demo.common.Constant.ORDER_PREVIEW_CONSUMER_GROUP;

@Service
@RocketMQMessageListener(topic = ORDER_PREVIEW,
        consumerGroup = ORDER_PREVIEW_CONSUMER_GROUP)
public class PreviewOrderService implements RocketMQListener<Order> {

    @Override
    public void onMessage(Order order) {

        if (repo.getOrder(order.getOrderId()).isPresent()) {
            return; // 订单已经入库，不再处理
        }

        // 实际库存校验
        Integer numbers = repertoryRepo.getNumbers(order.getProductId());
        if (numbers == null && numbers < order.getNumbers()) {
            // log 库存不足打印说明日志

            // 订单入库
            order.setOrderStatus(Order.OrderStatus.low_stocks);
            order.setUpdateTime(new Date().getTime());
            order.setMsg("库存不足：" + (order.getUpdateTime() - order.getCreateTime()));
            repo.putOrder(order);

            return;
        }

        // 创建并保持订单
        repo.putOrder(order);
        // 扣减库存
        repertoryRepo.takeOut(order.getProductId(), order.getNumbers());
        repertoryCache.takeOut(order.getProductId(), order.getNumbers());

        // 放入待支付检查队列
        Message message = MessageBuilder.withPayload(order).build();
        mqTemplate.syncSend(Constant.ORDER_TO_PAY, message,
                mqTemplate.getProducer().getSendMsgTimeout(), Constant.DelayTimeLevel);
    }

    private Repo repo;
    private RepertoryRepo repertoryRepo;
    private RepertoryCache repertoryCache;
    private RocketMQTemplate mqTemplate;

    public PreviewOrderService(Repo repo, RepertoryRepo repertoryRepo,
                               RepertoryCache repertoryCache, RocketMQTemplate template) {
        this.repo = repo;
        this.repertoryRepo = repertoryRepo;
        this.repertoryCache = repertoryCache;
        this.mqTemplate = template;
    }

}
